package com.hup.winHolderService.service;

import com.hup.utils.commons.hardware.HRobotJni;
import com.hup.winHolderService.security.SecurityService;
import com.hup.winHolderService.ws.WsClient;
import com.hup.winHolderService.ws.WsClientHandler;
import com.hup.winHolderService.ws.handler.WsRequestData;
import com.hup.winHolderService.ws.handler.WsRequestMethod;
import com.hup.winHolderService.ws.model.WsLoginReq;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.TimerTask;

/**
 * @author hugan
 * @date 2023/11/9
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WsService {

    private final SecurityService securityService;
    private final ScheduleService scheduleService;
    @Setter
    private WsClientHandler clientHandler;
    private KeyboardStateTask keyboardStateTask;

    private byte lastKeyboardState = 10;

    /**
     * 处理认证请求
     */
    @WsRequestMethod("wsLogin")
    public void wsLogin(@WsRequestData WsLoginReq req, WsClient client) {
        if (StringUtils.isNotBlank(req.getToken()) && securityService.checkToken(req.getToken())) {
            client.setHadAuth(true);
            log.info("认证成功={}", client.getUser());
            onClientChanged(true, client);
        } else {
            //被盗用
            log.warn("认证失败={}, {}", client.getUser(), req);
            client.doCloseSilent();
        }
    }

    public void onClientChanged(boolean isOnline, WsClient client) {
        boolean needRunTask = !clientHandler.getClients().isEmpty();
        log.info("needRunTask={}", needRunTask);
        if (needRunTask) {
            if (keyboardStateTask != null) return;
            keyboardStateTask = new KeyboardStateTask();
            scheduleService.getTimer().schedule(keyboardStateTask, 0, 1000);
        } else {
            if (keyboardStateTask == null) return;
            keyboardStateTask.cancel();
            keyboardStateTask = null;
        }
    }

    private class KeyboardStateTask extends TimerTask {

        @Override
        public void run() {
            byte state = HRobotJni.getKeyboardState();
            //log.info("keyboardStateTask.state={}", state);
            if (state != lastKeyboardState) {
                lastKeyboardState = state;
                clientHandler.sendToAll("onKeyboardState", state, null);
            }
        }
    }

}
